﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Backend.JYD.Model
{
    public class PageInfo
    {
        public int PageSize { get; set; }
        public int PageIndex { get; set; }
    }

    public class PageInfo<T> : PageInfo
    {
        public long ItemCount { get; set; }
        public int PageCount { get; set; }
        public List<T> PageList { get; set; }

        private PageInfo() { }

        public PageInfo(PageInfo info)
        {
            this.PageSize = info.PageSize;
            this.PageIndex = info.PageIndex;
            if (this.PageIndex <= 0) this.PageIndex = 1;
            if (this.PageSize <= 0) this.PageSize = 20;
        }

        public PageInfo(PageInfo info, IEnumerable<T> query)
            : this(info)
        {
            this.ItemCount = query.Count();
            this.PageCount = Convert.ToInt32(this.ItemCount / this.PageSize) + (this.ItemCount % this.PageSize == 0 ? 0 : 1);
            if (this.PageIndex > this.PageCount) this.PageIndex = this.PageCount;

            var temp = query.Skip((this.PageIndex - 1) * this.PageSize).Take(this.PageSize);
            this.PageList = temp == null ? null : temp.ToList();
        }
        public delegate TCast CastPastListHandle<TCast>(T info);
        public PageInfo<TCast> CastHandle<TCast>(CastPastListHandle<TCast> handle)
        {
            if(this.PageList == null) return null;

            List<TCast> temp = new List<TCast>();
            foreach (T info in this.PageList)
            {
                TCast cast = handle(info);
                if (cast != null)
                {
                    temp.Add(cast);
                }
            }
            var pageinfo = new PageInfo<TCast>();
            pageinfo.ItemCount = this.ItemCount;
            pageinfo.PageCount = this.PageCount;
            pageinfo.PageIndex = this.PageIndex;
            pageinfo.PageList = temp;
            pageinfo.PageSize = this.PageSize;

            return pageinfo;
        }
    }
}
